package com.hhxy.filter;

import com.hhxy.domain.LoginUser;
import com.hhxy.utils.JwtUtil;
import com.hhxy.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author ghp
 * @date 2023/3/9
 * @title 自定义的 Jwt 过滤器
 * @description 用于判断用户是否处于登录状态
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    /**
     * 过滤所有请求
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取Cookie中的token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            // token不存在，说明用户未登录，直接放行（放行后FilterSecurityInterceptor会直接报异常）
            filterChain.doFilter(request, response);
            return;
        }
        // 解析token
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        // 从 redis 中获取用户信息
        String redisKey = "login:" + userId;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if (Objects.isNull(loginUser)){
            // redis 中不存在该用户, 该token的TTL可能过期了
            throw new RuntimeException("用户登录已过期");
        }

        // 获取权限信息封装到Authentication中
        // 生成可信任的token。使用三个参数的构造器，表示当前用户是已认证的状态，不需要在进行认证了（两个参数的token是需要认证的）
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        // 重置认证信息，将用户信息存入SecurityContextHolder，方便后续过滤器获取认证信息
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 放行
        filterChain.doFilter(request, response);
    }
}
